package com.guxingke.typecho4j.jfinal.model;

import java.util.List;

import com.guxingke.typecho4j.util.PageBean;
import com.jfinal.plugin.activerecord.Model;

/**
 * typecho_options表 对应的model
 * */
public class Comment extends Model<Comment> {
	private static final long serialVersionUID = -1485818096843857845L;
	public static final Comment dao = new Comment();

	public List<Comment> getComments(PageBean pageBean) {
		String sql = "select * from typecho_comments order by created desc limit ?,?";
		return find(sql, pageBean.getStart(), pageBean.getPageSize());
	}

	public List<Comment> getRecentComments(int pageSize) {
		String sql = "select coid,cid,author,url,text from typecho_comments order by created desc limit 0,?";
		return find(sql, pageSize);
	}

	public List<Comment> getCommentsByCid(Long cid, PageBean pageBean) {
		List<Comment> results = null;
		String sql = "select * from typecho_comments where type = 'comment' and cid = ? and parent=? order by created asc limit ?,?";
		results = find(sql, cid, 0, pageBean.getStart(),
				pageBean.getPageSize());

		for (Comment comment : results) {
			comment.put("children", getCommentsByParentId(comment
					.getLong("coid")));
		}
		return results;
	}

	private List<Comment> getCommentsByParentId(Object coid) {
		String sql = "select * from typecho_comments where parent=? order by created asc";
		return find(sql, coid);
	}

	public Long getPublishedCommentsNum() {
		String sql = "select count(coid) as count from typecho_comments where type = 'comment' and  status='approved' group by type";
		Comment result = findFirst(sql);
		if (result == null) {
			return 0L;
		}
		return result.getLong("count");
	}

	public Long getWaitingCommentsNum() {
		String sql = "select count(coid) as count from typecho_comments where type = 'comment' and  status='waiting' group by type";
		Comment result = findFirst(sql);
		if (result == null) {
			return 0L;
		}
		return result.getLong("count");
	}

	public Long getSpamCommentsNum() {
		String sql = "select count(coid) as count from typecho_comments where type = 'comment' and  status='spam' group by type";
		Comment result = findFirst(sql);
		if (result == null) {
			return 0L;
		}
		return result.getLong("count");
	}

	public Long getCommentsNum() {
		String sql = "select count(coid) as count from typecho_comments";
		Comment result = findFirst(sql);
		if (result == null) {
			return 0L;
		}
		return result.getLong("count");
	}

	public void deleteComment(Long coid) {
		List<Comment> chirdren = getCommentsByParentId(coid);
		for (Comment comment : chirdren) {
			comment.delete();
		}
		deleteById(coid);
	}
}
